<script setup>
import { onMounted, ref } from 'vue';
import { getAgentdata, getgrouptoList, memberMigration } from '../../api/api';
import { ElMessage } from 'element-plus';
let total = ref(0)
let page = ref(1)
let pageSize = ref(10)
let agentData = ref([])
import AddUserGroup from './AddUserGroup.vue';
async function getAgent() {
    try {
        let res = await getAgentdata(page.value, pageSize.value)
        console.log(res);
        if (res.code == 200) {
            agentData.value = res.rows
            total.value = res.total
        }
    } catch (error) {
        console.log(error);

    }
}
onMounted(() => {
    getAgent()
})
async function getCurrentPage(e) {
    console.log(e);
    page.value = e
    try {
        let res = await getAgentdata(e, pageSize.value)
        console.log(res);
        if (res.code == 200) {
            agentData.value = res.rows
            total.value = res.total
        }
    } catch (error) {
        console.log(error);

    }

}
const levelMap = {
    6: 'T1',
    7: 'T2',
    8: 'T3',
    9: 'T4',
};
let passwordVisible = ref(false)
const resetFormRef = ref(null)
let grouptoList = ref([])
const resetForm = ref({
    migratestr: null
})
let adminIds = ref(0)
async function migrateHandler(adminId, total) {
    resetForm.value.migratestr = ""
    adminIds.value = adminId
    grouptoList.value = []
    console.log(adminId);
    passwordVisible.value = true
    if (total == 0) {
        return;
    }
    try {
        let res = await getgrouptoList(adminId)
        console.log(res);
        let arr = []
        if (res.code == 200) {
            if (res.data.length > 0) {
                res.data.forEach(item => {
                    arr.push({
                        label: item.nickname,
                        value: item.adminId
                    })
                })
                const uniqueArr = removeDuplicateObjects(arr, 'value');
                grouptoList.value = uniqueArr
            }
        }
    } catch (error) {
        console.log(error);
    }
}
function removeDuplicateObjects(arr, key) {
    const seen = new Set(); 
    return arr.filter(item => {
        if (seen.has(item[key])) {
            return false; 
        } else {
            seen.add(item[key]); 
            return true; 
        }
    });
}
let rulesobj = {
    migratestr: [
        {
            required: true,
            message: 'Please input a migratestr group',
            trigger: 'blur'
        }
    ]
}
async function reactpass() {
    if (resetForm.value.migratestr == '') {
        ElMessage.error('Please input a migratestr group')
        return;
    }
    console.log(adminIds.value);
    console.log(resetForm.value.migratestr);
    let requestData = {
        sourceAdminId: adminIds.value,
        targetAdminId: resetForm.value.migratestr
    }
    try {
        let res = await memberMigration(requestData)
        console.log(res);
        if (res.code == 200) {
            ElMessage.success(res.msg)
            passwordVisible.value = false
            getAgent()
        }

    } catch (error) {
        console.log(error);

    }

}
let addchuanadminId = ref(0)
function adduserList(adminId, total) {
    addchuanadminId.value = adminId
    console.log(addchuanadminId.value);
    if (total == 0) {
        return;
    }
    dialogFormVisible.value = true
}
let dialogFormVisible = ref(false)
function closefun() {
    dialogFormVisible.value = false
}
const hasPermission = (permission) => {
    const permissions = JSON.parse(localStorage.getItem("userdetail"))?.auths || [];
    if (permissions[0] === '*:*:*') {
        return true; 
    }
    return permissions.includes(permission);
};
</script>

<template>
    <div class="administrator">
        <div class="administratorbas">
            <div class="top">
                <span>Agent</span>
            </div>
            <div class="cont" v-if="hasPermission('user:group:query')">
                <div class="grid">
                    <div class="card" v-for="item in agentData">
                        <div class="info">
                            <div class="aline">
                                <span class="title">组等级: </span>
                                <span>
                                    {{ levelMap[item.userLevel] || '未知等级' }}
                                </span>
                            </div>
                            <div class="aline">
                                <span class="title">组名称: </span>
                                <span class="text" :title="item.nickname">{{ item.nickname }}</span>
                            </div>
                            <div class="aline">
                                <span class="title">总数: </span>
                                <span>{{ item.total }}</span>
                            </div>
                        </div>
                        <div class="buttons">
                            <img src="../../assets/images/tran2.png" alt="" width="25" height="25" class="migrate"
                                @click="migrateHandler(item.adminId, item.total)" v-has="hasPermission('user:group:edit')">
                            <img src="../../assets/images/gerenzhongxin.png" alt="" width="25" height="25"
                                class="migrate" @click="adduserList(item.adminId, item.total)">
                        </div>

                    </div>
                </div>
            </div>
            <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
                <el-pagination background layout="prev, pager, next" :page-count="Math.ceil(total / pageSize)"
                    style="text-align: end;" :current-page='page' @current-change="getCurrentPage" />
            </div>
            <el-dialog v-model="passwordVisible" title="Select the group for migration" width="500"
                modal-class="custom-modal" @close="passwordVisible = false">
                <!-- 使用 currentUser -->
                <br>
                <el-form :model="resetForm" :rules="rulesobj" ref="resetFormRef">
                    <el-form-item label="" prop="newpass">
                        <el-select v-model="resetForm.migratestr" placeholder="Please select Group migrated to"
                            style="width: 280px;">
                            <el-option v-for="item in grouptoList" :key="item.value" :label="item.label"
                                :value="item.value">
                                {{ item.label }}
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="passwordVisible = false">cancel</el-button>
                        <el-button type="primary" @click="reactpass()">sure</el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
    <AddUserGroup :dialogFormVisible="dialogFormVisible" :addchuanadminId="addchuanadminId" @close="closefun">
    </AddUserGroup>
</template>
<style lang="scss" scoped>
.administrator {
    padding: 15px;
    background-color: #eff1f4;

    .administratorbas {
        background-color: #fff;
        width: 100%;
        height: 88vh;
        border-radius: 10px 10px 0 0;

        .top {
            height: 50px;
            background-color: #f9f9f9;
            border-radius: 10px 10px 0 0;
            font-size: 20px;
            font-weight: bold;
            overflow: hidden;
            border-bottom: 1px solid #f1eded;

            span {
                display: block;
                margin: 10px 0 0 15px;
            }
        }

        .cont {
            padding: 20px;

            .one {
                margin: 10px;
                display: flex;
                padding: 10px;

                div {
                    margin-right: 20px;
                }
            }

            .exp {
                .export-excel {
                    margin-left: 20px;
                }
            }

            .tab {
                margin-top: 20px;
                width: 100%;
                position: relative;
                min-height: 300px;

                .el-table {
                    --el-table-header-bg-color: #fafafa;
                }

                .el-switch {
                    --el-switch-on-color: #45d585;
                }

                .more-button {
                    margin-left: 8px;
                    margin-top: 3px;
                    /* 为“更多”按钮添加左边距 */
                    color: #409EFF;
                    outline: none;

                    /* Element Plus 主题色 */
                    &:hover {
                        color: #66b1ff;

                        /* 鼠标悬停时的颜色 */
                    }
                }
            }
        }
    }

    /* 如果使用 scoped，需要添加 ::v-deep */
    ::v-deep .custom-modal {
        background-color: rgba(0, 0, 0, .5);
        /* 设置弹窗背景颜色为半透明 */
    }

    /* 或者更精确的定位 */
    ::v-deep .custom-modal .el-overlay {
        background-color: rgba(0, 0, 0, 0.8);
    }

    .grid {
        width: 100%;
        display: grid;
        // grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 40px;
        // 默认：小屏时 2 列 
        // grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        grid-template-columns: repeat(2, 1fr);

        // 中等屏幕（比如 1024px ~ 1440px）
        @media screen and (min-width: 1024px) {
            grid-template-columns: repeat(4, 1fr);
        }

        // 大屏（比如 1440px 及以上）
        @media screen and (min-width: 1440px) {
            grid-template-columns: repeat(5, 1fr); // 或者 4 列 / minmax(320px, 1fr)
        }
    }

    .card {
        background-color: white;
        border-radius: 8px;
        padding: 20px;
        display: flex;
        align-items: center;
        box-shadow: 0 2px 8px rgb(0, 193, 212);
        // border: 1px solid rgb(0,193,212);
        padding: 50px;
        position: relative;
    }



    .aline {
        font-size: 16px;
        color: #333;
        margin-bottom: 10px;
        line-height: 25px;
        display: flex;
        /* 将 .aline 设为 Flex 容器 */
        align-items: center;
        /* 垂直居中对齐 */
    }

    .title {
        font-weight: bold;
        color: #333;
    }

    overflow: visible;

    .text {
        width: 10ch;
        /* 根据需要调整宽度 */
        white-space: nowrap;
        /* 禁止文本换行 */
        overflow: hidden;
        /* 隐藏超出部分 */
        text-overflow: ellipsis;
        /* 超出部分显示省略号 */
        // display: inline-block;
        /* 确保 width 生效 */
    }

    .buttons {
        position: absolute;
        right: 25px;
        /* 距离右侧的距离 */
        top: 20%;
        /* 垂直居中 */
        /* 垂直居中 */
        display: flex;
        flex-direction: column;
        /* 按钮竖向排列 */
        gap: 10px;
        /* 按钮之间的间距 */
    }
}
</style>